package com.bdsc.blogs.mirror.controller;

import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 马凯林
 */
@Controller
@RequestMapping("/")
public class IndexController {

  private static final Logger logger = LogManager.getLogger(IndexController.class);

  @Autowired
  private Registration registration;

  @Autowired
  private DiscoveryClient client;

  @RequestMapping("/index")
  public String index() {
    ServiceInstance instance = serviceInstance();
    String result = "/testBalance, host:port=" + instance.getUri()  + ", "
        + "service_id:" + instance.getServiceId();
    logger.info(result);
    return "index";
  }

  public ServiceInstance serviceInstance() {
    List<ServiceInstance> list = client.getInstances(registration.getServiceId());
    if (list != null && list.size() > 0) {
      for (ServiceInstance itm : list) {
        if (itm.getPort() == 8080) {
          return itm;
        }
      }
    }
    return null;
  }

}
